package com.huilian.iotbox.mqtt.server.base.service.impl;

import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.po.Product;
import com.huilian.iotbox.mqtt.server.base.dao.ProductDao;
import com.huilian.iotbox.mqtt.server.base.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author 谢洛涛
 * @date 2021/8/31 12:23
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductDao productDao;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public Product findOneProductByLoginId(int loginId) {

        final String key = String.format(RedisKey.PRODUCT_INFO, loginId);
        Product product = (Product) redisCacheTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(product)) {
            Product productCondition = new Product();
            productCondition.setLoginId(loginId);
            product = this.findOneProductByCondition(productCondition);

            if (!StringUtils.isEmpty(product)) {
                redisCacheTemplate.opsForValue().set(key, product, 1, TimeUnit.DAYS);
            }
        }

        return product;
    }

    /**
     * 根据条件查一个产品
     *
     * @param productCondition
     * @return
     */
    @Override
    public Product findOneProductByCondition(Product productCondition) {
        return productDao.findOneProductByCondition(productCondition);
    }
}
